package com.cnzhy.handler;

import com.cnzhy.annotation.JwtToken;
import com.cnzhy.utils.JwtUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;

/**
 * @Author: zhaoyan5
 * 自定义方法参数拦截器 HandlerMethodArgumentResolver
 */
public class JwtTokenArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * 判断参数上是否有JwtToken注解
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JwtToken.class);
    }

    /**
     * 检查 request 请求中有没有 "Authorization" 的 http header
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String authorization = request.getHeader("Authorization");
        if (authorization == null) {
            return "没有找到认证";
        }
        Annotation[] methodAnnotations = parameter.getParameterAnnotations();
        for (Annotation methodAnnotation : methodAnnotations) {
            if (methodAnnotation instanceof JwtToken) {
                JwtToken token = (JwtToken) methodAnnotation;
                return token != null ? JwtUtil.get(authorization, token.value()) : null;
            }
        }
        return "没有认证成功";
    }

}
